import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as dat from 'dat.gui'
var w = window.innerWidth
var h = window.innerHeight
var scene, camera, renderer,gui,cameraParams,light,lightParams


function main() {
  init()
  setLine()
  setLight()
  setGui()
  render()
}

function init() {
  // 创建场景对象Scene
  scene = new THREE.Scene();

  camera =  new THREE.PerspectiveCamera(75, w / h, 1, 1000)
  camera.position.x = 0
  camera.position.y = 0
  camera.position.z = 100
  camera.up.x = 0
  camera.up.y = 1
  camera.up.z = 0
  camera.lookAt({ x: 0, y: 0, z: 0 })

  renderer = new THREE.WebGLRenderer()
  renderer.setClearColor('#8edee2')
  renderer.setSize(w, h)
  document.body.appendChild(renderer.domElement)
}

function setLine() {
  var geometry = new THREE.CylinderGeometry(30, 50, 100, 40)

  var material = new THREE.MeshLambertMaterial({ color: 0xfed1e2 })

  var mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function setLight(){
  light = new THREE.PointLight(0xff0,1,1000,1)
  scene.add(light)
}

function setGui() {
  gui = new dat.GUI();
  var c = gui.addFolder('相机')
  var l = gui.addFolder('平行光源')
  cameraParams =  {
      fov : 45
  }
  lightParams = {
    x:0,
    y:0,
    z:0,
    intensity:1,
    decay:1
  }
  c.add(cameraParams,'fov', 0, 180).name('视角大小')
  l.add(lightParams,'z',0,1000).name('光源的z位置')
  l.add(lightParams,'intensity',0,1).name('光源的强度')
  l.add(lightParams,'decay',0,1).name('衰减')
  l.open()
}

function changeCamera(){
  camera.fov = cameraParams.fov
  camera.updateProjectionMatrix()
}

function changeLight(){
  light.position.set(lightParams.x,lightParams.y,lightParams.z)
  light.intensity = lightParams.intensity
  light.decay = lightParams.decay
}

function render() {
  changeCamera()
  changeLight()
  // console.log('=======',params.fov);
  
  renderer.render(scene, camera)
  requestAnimationFrame(render)
}

main()
/** --------------------鼠标控件对象--------------------- */
let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
controls.addEventListener("change", render); //监听鼠标、键盘事件